#pragma once

#include <iostream>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using namespace LogModule;

const int defaultfd = -1;

class UdpServer
{
public:
    UdpServer(const std::string &ip, uint16_t port)
        : _sockfd(default),
          _ip(ip),
          _port(port)
    {
    }

    void Init()
    {
        //1.创建套接字
        _socketfd=socket(AF_INET,SOCK_DGRAM,0);
        if(_sockfd<0)
        {
            LOG(LogLevel::FATAL)<<"socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO)<<"socket success,sockfd:"<<_sockfd;

        // 2. 绑定socket信息，ip和端口， ip(比较特殊，后续解释)
        // 2.1 填充sockaddr_in结构体
        struct sockaddr_in local;
        bzero(&local,sizeof(local));
        local.sin_family=AF_INET;

        local.sin_port=htons(_port);
        // IP也是如此，1. IP转成4字节 2. 4字节转成网络序列 -> in_addr_t inet_addr(const char *cp);


        int n=bind(_socketfd,(struct sockaddr *)&local,sizeof(local));
	if(n<0)
	{
		LOG(LogLevel::FATAL)<<"bind error";
		exit(2);
	}
	LOG(LogLevel::INFO)<<"bind success,sockfd:"<<_sockfd;
    }

    void Start()
    {
	    isrunninf=true;
	    while(_isrunning)
	    {
		    char buffer[1024];
		    struct sockaddr_in peer;
		    socklen_t len=sizeof(peer);
		    ssize_t s=recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr *)&peer,&len);
		    if(s>0)
		    {
			    int peer_port

		    }


	    }
    }

    ~UdpServer()
    {
    }

    private:
    int _sockfd;
    uint16_t _port;
    std::string _ip;
};
